//
//  MyOrderNineModeView.m
//  X-Touch2
//
//  Created by shengchao yang on 12-3-15.
//  Copyright (c) 2012年 foxhis. All rights reserved.
//

#import "MyOrderNineModeView.h"
#import "Singleton.h"
#import "GridViewItemMyOrder.h"
#import "MAlertView.h"
#import "Common.h"
#import "FileManager.h"
#import "NSString+Additions.h"

#import "Http.h"
#import "JSON.h"
#import "DownloadFromInternet.h"

@interface MyOrderNineModeView(Private)
-(void) refreshLabel;
-(void) sendMyOrderAnyway;
@end

@implementation MyOrderNineModeView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

#pragma mark - UIGridViewDataSource
-(NSInteger) gridViewRows:(UIGridView *)gridView{
    return 3;
}
-(NSInteger) gridViewCols:(UIGridView *)gridView{
    return 3;
}
-(NSInteger) gridViewTotalCount:(UIGridView *)gridView{
    return [AppSession.myOrderDishes count];
}
-(GridViewItem *) gridView:(UIGridView *)gridView1 itemAtIndex:(NSInteger)index{
    NSString *CellIdentifier = @"CellIdentifier1";
    GridViewItemMyOrder *item = (GridViewItemMyOrder *)[gridView1 dequeueReusableCellWithIdentifier:CellIdentifier];
    if (item == nil){
        item = [[GridViewItemMyOrder alloc] init];
    }
    
//    GridViewItemMyOrder *item = [[GridViewItemMyOrder alloc] init];
    MyOrderDishes *tempPlu = (MyOrderDishes *)[AppSession.myOrderDishes objectAtIndex:index];
    [item setData:tempPlu];
    return item;
}
-(BOOL) gridViewPageControlEnable:(UIGridView *)gridView{  //是否使用pageControl控件
    return NO;
}
-(BOOL) gridViewDirection:(UIGridView *)gridView{          //滑动的方向(YES-横向默认  NO-纵向)
    return NO;
}
-(BOOL) gridViewShowScrollIndicator:(UIGridView *)gridView{//是否显示滑动条Indicator(默认NO)
    return YES;
}
#pragma mark - UIGridViewDelegate
-(void) gridView:(UIGridView *)gridView didSelectItemAtIndex:(NSInteger)index{
    MyNSLog(@"弹出全屏窗口 index=%d", index);
    AppSession.myOrderPluIndex = index;
    AppSession.fullScreenType = 2;
    postN(SysMsg_RootView_PopOutPluPlu);//弹出大图模式
}
- (IBAction)buttonClicked:(id)sender {
    if (AppSession.isAnimating) {
        MyNSLog(@"上一个动画还未结束...");
        return;
    }
    [AppSession playMusic:VoiceFile(@"clicked.caf")];
    NSInteger bid = [sender tag];
    
    NSInteger newBid = bid - TagOfUIButton;
    if ([AppSession.currentOrderMenu.momSendErr isEqualToString:@"1"] && (newBid==0 || newBid==4)) {
        postN(@"SysMsg_RootView_AlertErrMsg");
        return;
    }
    
    if (bid == TagOfUIButton) {
        MyNSLog(@"整单备注");
        NSDictionary *infos = [NSDictionary dictionaryWithObjectsAndKeys:nil, @"pluObj",nil];
        postNWithInfos(@"SysMsg_RootView_PopOutSelectCookWithInfo", nil, infos);
    }else if (bid == TagOfUIButton + 1) {
        MyNSLog(@"清空");
        UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"删除确认") 
                                                        message:TranslateStr(@"确定要清空所有已点的菜？")
                                                       delegate:self 
                                              cancelButtonTitle:TranslateStr(@"取消") 
                                              otherButtonTitles:TranslateStr(@"确定"), nil];
        alert.tag = TagOfUIAlertView;
        [alert show];
        [alert release];
    }else if (bid == TagOfUIButton + 2) {
        MyNSLog(@"保存");
        NSDictionary *infos = [NSDictionary dictionaryWithObjectsAndKeys:@"save", @"obj",nil];
        postNWithInfos(@"SysMsg_RootView_PopOutMyOrderMenuManagement", nil, infos);
    }else if (bid == TagOfUIButton + 3) {
        MyNSLog(@"发送");
        if ([AppSession.currentOrderMenu.ptDescripts isEqualToString:@"未开台"]) {
            UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"桌号未选择！") 
                                                            message:TranslateStr(@"请先开台选择桌号和人数！")
                                                           delegate:nil 
                                                  cancelButtonTitle:TranslateStr(@"返回") 
                                                  otherButtonTitles: nil];
            [alert show];
            [alert release];
        }else {
            [AppSession initMyOrderDishes];
            [AppSession initMyOrderPluPkgs:nil];//初始化已点套餐明细数组
            BOOL isNeedCheck = NO;
            for (MyOrderDishes * temp in AppSession.myOrderDishes) {
                if ([temp.modNumber floatValue] == 0 || [temp.modPrice floatValue] == 0) {
                    isNeedCheck = YES;
                    break;
                }
            }
            
            if (isNeedCheck) {
                UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"提示") 
                                                                message:TranslateStr(@"价格或数量为0确认")
                                                               delegate:self 
                                                      cancelButtonTitle:TranslateStr(@"返回修改") 
                                                      otherButtonTitles:TranslateStr(@"继续送单"), nil];
                alert.tag = TagOfUIAlertView + 1;
                [alert show];
                [alert release];
            }else {
                [self sendMyOrderAnyway];
            }
        }
    }else if(bid == TagOfUIButton + 4){
        UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"提示") 
                                                        message:TranslateStr(@"清空烧法确认")
                                                       delegate:self 
                                              cancelButtonTitle:TranslateStr(@"取消") 
                                              otherButtonTitles:TranslateStr(@"确定"), nil];
        alert.tag = TagOfUIAlertView + 3;
        [alert show];
        [alert release];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == TagOfUIAlertView) {
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderDishes where momLocalMenu='%@'",AppSession.currentOrderMenu.momLocalMenu]];
            [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderPluPkgs where momLocalMenu='%@'",AppSession.currentOrderMenu.momLocalMenu]];
            
            //修改本地主单号
            NSString * oldLocalMenu = AppSession.currentOrderMenu.momLocalMenu;
            NSString * newLocalMenu = LocalMenu;//生成新的本地主单号
            [DataBaseAccess Update:[NSString stringWithFormat:@"update MyOrderMenus set momLocalMenu='%@',momSendErr='0' where momLocalMenu='%@'",newLocalMenu,oldLocalMenu]];
            AppSession.currentOrderMenu.momSendErr = @"0";//默认未发送
            AppSession.currentOrderMenu.momLocalMenu = newLocalMenu;
            
            postN(@"SysMsg_MyOrderNineModeView_refreshNineMode");
        }
    }else if(alertView.tag == TagOfUIAlertView + 1){
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            [self sendMyOrderAnyway];
        }
    }else if(alertView.tag == TagOfUIAlertView + 2){
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            MyNSLog(@"调用送单函数...");
            UITextField * userField = (UITextField *)[alertView viewWithTag:TagOfUITextField];
            UITextField * passField = (UITextField *)[alertView viewWithTag:TagOfUITextField+1];
            NSString * empno = FormatNilObject(userField.text);
            NSString * password = FormatNilObject(passField.text);
            
            //弹出正在处理窗口
            NSDictionary *infos = [NSDictionary dictionaryWithObjectsAndKeys:TranslateStr(@"正在发送"),@"message",nil];
            postNWithInfos(@"SysMsg_RootView_ShowMyProcessView", self, infos);
            NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:empno,@"empno",password,@"password", nil];
                        
            NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(startSendMyOrder:) object:dict];
            [thread start];//启动更新入口
            [thread release];  
        }
    }else if(alertView.tag == TagOfUIAlertView + 3){
        if (buttonIndex == alertView.firstOtherButtonIndex) {
            [DataBaseAccess Update:[NSString stringWithFormat:@"update MyOrderDishes set modCook='' where momLocalMenu='%@'", AppSession.currentOrderMenu.momLocalMenu]];
        }
    }
}
//弹出密码输入框
-(void) sendMyOrderAnyway{
    NSString * msg = [NSString stringWithFormat:@"%@：%@[%@]",TranslateStr(@"桌号"),JsonField(AppSession.currentOrderMenu.ptDescripts),AppSession.currentOrderMenu.ptTableNo];
    MAlertView *alert =[[ MAlertView alloc] initWithTitle:TranslateStr(@"送单确认") 
                                                  message:msg
                                                 delegate:self 
                                        cancelButtonTitle:TranslateStr(@"取消") 
                                        otherButtonTitles:TranslateStr(@"确定"), nil];
    alert.tag = TagOfUIAlertView + 2;
    UITextField * username = [[UITextField new] autorelease];
    username.tag = TagOfUITextField;
    UITextField * password = [[UITextField new] autorelease];
    password.tag = TagOfUITextField + 1;
    password.secureTextEntry = YES;
    [alert addTextField:username placeHolder:TranslateStr(@"用户名")];
    [alert addTextField:password placeHolder:TranslateStr(@"密码")];
    username.text = AppSession.currentOrderMenu.peEmpno;
    [alert show];
    [alert release];
}

//发送线程
-(void) startSendMyOrder:(NSDictionary *)obj{  
    NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
    NSString * tempLanguage = [NSString stringWithString:AppSession.language];//保存当前语言
    AppSession.language = DefaultLang;
    NSString * ipadmenu = AppSession.currentOrderMenu.momLocalMenu;
    NSString * empno = [obj objectForKey:@"empno"];
    NSString * password = [obj objectForKey:@"password"];
    NSString * persons = AppSession.currentOrderMenu.persons;
    NSString * tableno = AppSession.currentOrderMenu.ptTableNo;
    NSString * UDID = AppSession.ipadUdid;
    NSString *sendOrderJson=[NSString stringWithFormat:@"{\"ipadmenu\":\"%@\",\"empno\":\"%@\",\"password\":\"%@\",\"persons\":\"%@\",\"tableno\":\"%@\",\"UDID\":\"%@\",\"myorders\":",ipadmenu,empno,password,persons,tableno,UDID];
    
    //组装我的点单json串
    NSString *myorderJson=@"[";
    int indexMyOrder=0;
    for (MyOrderDishes * temp in AppSession.myOrderDishes) {
        indexMyOrder++;
        myorderJson=[myorderJson stringByAppendingFormat:@"{\"ppCode\":\"%@\",",temp.ppCode];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppName\":\"%@\",",JsonField(temp.modDescripts)];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppNumber\":\"%@\",",temp.modNumber];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppPrice\":\"%@\",",temp.modPrice];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppUnit\":\"%@\",",JsonField(temp.modUnits)];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppCook\":\"%@\",",temp.modCook];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppTemp\":\"%@\",",temp.modPluPlu.ppTemp];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppType\":\"%@\"}",temp.modPluPlu.ppType];
        if (indexMyOrder<[AppSession.myOrderDishes count]) {
            myorderJson=[myorderJson stringByAppendingFormat:@","];
        }        
    }
    //--------------------组装套餐--------------------
    myorderJson=[myorderJson stringByAppendingFormat:@"],\"plupkgs\":["];
    indexMyOrder=0;
    for (MyOrderPluPkgs * tempPkg in AppSession.myOrderPluPkgs) {
        indexMyOrder++;
        myorderJson=[myorderJson stringByAppendingFormat:@"{\"ppCode\":\"%@\",",tempPkg.ppCode];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgCode\":\"%@\",",tempPkg.pkgCode];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgName\":\"%@\",",JsonField(tempPkg.pkgDescripts)];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgNumber\":\"%@\",",tempPkg.pkgNumber];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgPrice\":\"%@\",",tempPkg.pkgPrice];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgUnit\":\"%@\",",JsonField(tempPkg.pkgUnit)];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgCook\":\"%@\",",tempPkg.pkgCook];
        myorderJson=[myorderJson stringByAppendingFormat:@"\"pkgTemp\":\"%@\"}",tempPkg.pkgTemp];
        if (indexMyOrder < [AppSession.myOrderPluPkgs count]) {
            myorderJson=[myorderJson stringByAppendingFormat:@","];
        }
    }
    AppSession.language = tempLanguage;
    //--------------------end-------------------
    
    sendOrderJson=[sendOrderJson stringByAppendingFormat:@"%@]}",myorderJson];//最终要发送的json串
    MyNSLog(@"sendOrderJson=%@", sendOrderJson);
    
    //接收返回信息 
    NSError *outError = nil;
    NSString *sendResult = [DownloadFromInternet sendMyOrders:sendOrderJson Error:&outError];
    NSDictionary *resultDic = [sendResult JSONValue];
    NSString *errCode = @"";
    NSString *errMsg = @"";
    if ([resultDic count]==0) {
        errCode=@"88888";
        errMsg=@"送单失败！请检查网络是否连接以及网站接口是否开启！";//[NSString stringWithFormat:@"%@\r\n%@",[outError localizedDescription],sendResult];
        [AppSession.currentOrderMenu updateSendErr];//设置正在发送
    }
    else{
        errCode=[resultDic objectForKey:@"code"];
        errMsg=[resultDic objectForKey:@"message"];
    }
    MyNSLog(@"sendResult=%@",sendResult);
    
    //返回结果处理
    postN(@"SysMsg_RootView_CloseMyProcessView");//关闭弹出窗口
    NSString * alertTitle = @"送单失败！";
    NSString * alertMessage = [NSString stringWithFormat:@"(%@)%@",errCode,errMsg];
    if ([errCode isEqualToString:@"30002"]) {//送单成功!
        alertTitle = @"送单成功！";        
        [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderDishes where momLocalMenu='%@'",AppSession.currentOrderMenu.momLocalMenu]];
        [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderPluPkgs where momLocalMenu='%@'",AppSession.currentOrderMenu.momLocalMenu]];
        [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderMenus where momLocalMenu='%@'",AppSession.currentOrderMenu.momLocalMenu]];
        [AppSession initCurrentOrderMenu:AppSession.bookIndex];//重新生成主单
        postN(@"SysMsg_MyOrderNineModeView_refreshNineMode");
    }
    UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:alertTitle
                                                    message:alertMessage
                                                   delegate:nil 
                                          cancelButtonTitle:TranslateStr(@"确定")
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    [pool release];
}

//刷新界面
-(void) refreshNineMode{
    [AppSession initMyOrderDishes];
    [gridView reloadData];
    [self refreshLabel];
    postN(@"SysMsg_MyOrderView_refreshToolBar");
}
-(void) refreshLabel{
    ((UILabel *)[self viewWithTag:TagOfUILabel]).text = [NSString stringWithFormat:@"%0.2f",[DataBaseAccess getTotalNumber]];
    ((UILabel *)[self viewWithTag:TagOfUILabel+1]).text = [NSString stringWithFormat:@"￥%0.2f",[DataBaseAccess getTotalAmount]];
    
    [(UILabel *)[self viewWithTag:TagOfUILabel+2] setText:[NSString stringWithFormat:@"%@：",TranslateStr(@"总份数")]];
    [(UILabel *)[self viewWithTag:TagOfUILabel+3] setText:[NSString stringWithFormat:@"%@：",TranslateStr(@"预计消费")]];
    [(UILabel *)[self viewWithTag:TagOfUILabel+4] setText:TranslateStr(@"以下是所有点的菜")];
    
    [(UIButton *)[self viewWithTag:TagOfUIButton+0] setTitle:TranslateStr(@"整单备注") forState:UIControlStateNormal];
    [(UIButton *)[self viewWithTag:TagOfUIButton+4] setTitle:TranslateStr(@"清空烧法") forState:UIControlStateNormal];
    [(UIButton *)[self viewWithTag:TagOfUIButton+1] setTitle:TranslateStr(@"清空") forState:UIControlStateNormal];
    [(UIButton *)[self viewWithTag:TagOfUIButton+2] setTitle:TranslateStr(@"保存") forState:UIControlStateNormal];
    [(UIButton *)[self viewWithTag:TagOfUIButton+3] setTitle:TranslateStr(@"送单") forState:UIControlStateNormal];
}
-(void) deleteMyOrderDish:(NSNotification *)note{
    NSDictionary *infos = [note userInfo];
	if ([infos objectForKey:@"ppCode"] && [infos objectForKey:@"modPrice"] && [infos objectForKey:@"modTime"]) {
        NSString * ppCode = (NSString *)[infos objectForKey:@"ppCode"];
        NSString * modPrice = (NSString *)[infos objectForKey:@"modPrice"];
        NSString * modTime = (NSString *)[infos objectForKey:@"modTime"];
        
        [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderDishes where momLocalMenu='%@' and ppCode='%@' and modPrice='%@' and modTime='%@'",AppSession.currentOrderMenu.momLocalMenu,ppCode,modPrice,modTime]];
        [DataBaseAccess Update:[NSString stringWithFormat:@"delete from MyOrderPluPkgs where momLocalMenu='%@' and ppCode='%@'",AppSession.currentOrderMenu.momLocalMenu,ppCode]];
    }
    postN(@"SysMsg_MyOrderNineModeView_refreshNineMode");
}

- (void)drawRect:(CGRect)rect{
    addNObserver(@selector(refreshNineMode), @"SysMsg_MyOrderNineModeView_refreshNineMode");
    addNObserver(@selector(deleteMyOrderDish:), @"SysMsg_MyOrderNineModeView_deleteMyOrderDish");
    [self refreshNineMode];
    
    [self setFrame:CGRectMake(0, 53, 1024, 715)];
    
    //用自定义的九宫格view替换占位用的普通view，同时移除普通view
    UIView *tempView = (UIView *)[self viewWithTag:TagOfUIView];
    CGRect frame = tempView.frame;
    [tempView removeFromSuperview];
    
    gridView = [[UIGridView alloc] initWithTarget:self withFrame:frame withTag:TagOfUIGridView];
    [self addSubview:gridView];
}
-(void)dealloc{
    MyNSLog(@"GuestNineModeView is deallocing...");
    removeNObserver(@"SysMsg_MyOrderNineModeView_refreshNineMode");
    removeNObserver(@"SysMsg_MyOrderNineModeView_deleteMyOrderDish");
    [gridView release];
    gridView = nil;
    [super dealloc];
}
@end
